<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use library\Controller;
use library\service\AdminService;
use library\service\CaptchaService;
use library\service\SystemService;
use library\tools\Data;
use think\Db;
use think\facade\Request;
use think\facade\Config;
use think\facade\App;
/*工具*/
use redis\Redis;
use \Yunpian\Sdk\YunpianClient;
/**
 * 用户登录管理
 * Class Login
 * @package app\admin\controller
 */
class Login extends Controller
{

    /**
     * 后台登录入口
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
// var_dump($this->request->param('password'));
// var_dump(md5('admin'.Config::get('salt')));
// 	exit();


        if (Request::isGet()) {
            if (AdminService::instance()->isLogin()) {
                $this->redirect('@admin');
            } else {
                $this->title = '系统登录';
                $this->captcha_type = 'login_captcha';
                $this->captcha_token = Data::uniqidDateCode(18);
                $this->app->session->set($this->captcha_type, $this->captcha_token);
                $this->devmode = SystemService::instance()->checkRunMode('dev');
                $this->fetch();
            }
        } else {
            $login_type = $this->request->param('login_type');
            if($login_type == '1'){
                $data = $this->_vali([
                    'username.require' => '登录账号不能为空!',
                    'username.min:3'   => '登录账号长度不能少于4位有效字符！',
                    'password.require' => '登录密码不能为空！',
                    'password.min:4'   => '登录密码长度不能少于4位有效字符！',
                    'verify.require'   => '图形验证码不能为空！',
                    'uniqid.require'   => '图形验证标识不能为空！',
                ]);
                if (!CaptchaService::instance()->check($data['verify'], $data['uniqid'])) {
                    $this->error('图形验证码验证失败，请重新输入!');
                }
            }
            if($login_type == '2'){
                $data = $this->_vali([
                    'phone.require' => '登录手机号不能为空!',
                    'phone.min:11'   => '登录手机号长度不能少于11位有效字符！',
                    'code.require' => '登录验证码不能为空！',
                    'code.min:6'   => '登录验证码长度不能少于6位有效字符！',
                    // 'verify.require'   => '图形验证码不能为空！',
                    // 'uniqid.require'   => '图形验证标识不能为空！',
                ]);

                $data['username'] = $data['phone'];
            }

            $map = ['is_deleted' => '0', 'username' => $data['username']];
            $user = Db::name('SystemUser')->where($map)->order('id desc')->find();
            
            $error_arr[0] = empty($user)?true:false;
                //$this->error('登录账号或密码错误，请重新输入1!');

            if($error_arr[0]){
                $map = ['is_deleted' => '0', 'phone' => $data['username']];
                $user = Db::name('SystemUser')->where($map)->order('id desc')->find();
                $error_arr[0] = empty($user)?true:false;
            }
            if($error_arr[0]){
                // $dbconf = $this->getconfig('vister_db');
                // $goh5 = Db::connect($dbconf)->table('image_list')->where(['id'=>4])->find();
                // $this->assign('goh5',$goh5);
                $this->error('用户不存在,请注册.',[],400);}


            if ($login_type == '1' && $user['password'] !== md5($data['password'].Config::get('salt'))) {
                $this->error('登录账号或密码错误，请重新输入!');
            }
            if($login_type == '2'){
                $redis = new Redis;
                $confirm_code = $redis::get('pc_phone_Message_login_'.$data['phone']);
                if(!$confirm_code){$this->error('验证码无效,请稍后再试');}
                if($data['code'] != $confirm_code ){$this->error('验证码错误,请重新登录');}
                $redis::del('pc_phone_Message_login_'.$data['phone']);

            }

            // if (md5("{$user['password']}{$data['uniqid']}") !== $data['password']) {
            //     $this->error('登录账号或密码错误，请重新输入2!');
            // }

			//  if (md5("{$user['password']}") !== $data['password']) {
			//     $this->error('登录账号或密码错误，请重新输入2!');
			// }
            if (empty($user['status'])) {
                $this->error('账号已经被禁用，请联系管理员!');
            }
            Db::name('SystemUser')->where(['id' => $user['id']])->update([
                'login_ip'  => Request::ip(),
                'login_at'  => Db::raw('now()'),
                'login_num' => Db::raw('login_num+1'),
            ]);
            $this->app->session->set('user', $user);
            AdminService::instance()->apply(true);
            sysoplog('系统管理', '用户登录系统后台成功');
            $this->success('登录成功', url('@admin'));
			// return alert('登录成功',url('@admin'),6);
        }
    }

    /**
     * 生成验证码
     * 需要指定类型及令牌
     */
    public function captcha()
    {
        $image = CaptchaService::instance();
        $this->type = input('type', 'captcha-type');
        $this->token = input('token', 'captcha-token');
        $captcha = ['image' => $image->getData(), 'uniqid' => $image->getUniqid()];
        if ($this->app->session->get($this->type) === $this->token) {
            $captcha['code'] = $image->getCode();
            $this->app->session->delete($this->type);
        }
        $this->success('生成验证码成功', $captcha);
    }
	
	//注册
		public function register(){
            $dbconf = $this->getconfig('vister_db');
            $goh5 = Db::connect($dbconf)->table('image_list')->where(['id'=>4])->find();
            $this->assign('goh5',$goh5['base_img']);
			if($this->request->isPost()){
		$username = trim($this->request->param('username')); 
		$password = trim($this->request->param('password')); 
		$password_confirm = trim($this->request->param('password_confirm')); 
	
		if( empty($password) || empty($password_confirm) ||($password_confirm!=$password)){
			return alert('密码不一致，请重新输入！',url('@admin/login/register'),5);

			// $this->error('密码不一致，请重新输入！',url('login/index'));
	        // return ['message'=>'密码不能为空','code'=>'400'];
		}
		
			$userData =  Db::name('SystemUser')->where(['username' => $username]) ->find();
		if( $userData ){
			return alert('用户名已存在，请重新输入！',url('@admin/login/register'),5);
			// $this->error('用户名已存在，请重新输入！',url('@admin/login/register'));
		    // return ['message'=>'该用户已存在','code'=>'400'];
		}
		  $rule=  '/^0?(13|14|15|17|18)[0-9]{9}$/';
		   $result = preg_match($rule, $username);
		    // 'require|max:11|/^1[3-8]{1}[0-9]{9}$/';
		 
		
			if( !$result){
			return alert('用户名不是手机号，请重新输入！',url('@admin/login/register'),5);
			// $this->error('用户名已存在，请重新输入！',url('@admin/login/register'));
		    // return ['message'=>'该用户已存在','code'=>'400'];
		}
		
		$data = ['username' => $username,'password' => md5($password.Config::get('salt'))];
		$userData =  Db::name('SystemUser')->insert($data);
		 
	    if( $userData ){
			// $data ='注册成功';
   //              $this->assign('data',$data);
			// $this->success('注册成功');
			// $this->success('注册成功',url('login/index'));
			
			return alert('注册成功',url('@admin/login'),6);
			
					// $postData = input('post.');
		// 然后进行业务逻辑的执行，并根据执行结果返回$res来触发相应的返回
		// if($postData['test']===$postData['name']){
		// 	$res=true;
		// }else{
		// 	$res='不相等（这里是错误提示）';
		// }
		// $res=true;
		// 根据$res的值返回
		// if($res === true){
		// $result['msg'] = '注册成功了';
		// $result['icon'] = 1;
		//icon用于layer创建alert前面的图标
// 	}else{
// 		$result['msg'] = $res;
// 		$result['icon'] = 2;
// 	}
// exit(json_encode($result));
			// return json('注册成功');
			//  $this->redirect('@admin/login');
	        // return json(['message'=>'注册成功','code'=>'200']);
			// return alert('注册成功','@admin/login');
	    }
		
	}
	return $this->fetch();
		// $confirm = md5($password.Config::get('salt'));
	 //    if ( $userData['password'] !== $confirm ){
	 //        return ['message'=>'密码错误','code'=>'400'];
	 //    }
		
		// $userData->password = md5($password_confirm.Config::get('salt'));
		// $userData->save();
		//  Db::name('SystemUser')->where(['id' => $user['id']])->update([
		//     'login_ip'  => Request::ip(),
		//     'login_at'  => Db::raw('now()'),
		//     'login_num' => Db::raw('login_num+1'),
		// ]);
		// Data::add($this->table, ['username' => $post['username'], 'password' => md5($post['password'])]);
		// 
		// return ['message'=>'保存成功','code'=>200];
	}
    /**
     * 用户注册后台
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-26T14:09:12+0800
     * @LastTime     2020-11-26T14:09:12+0800
     * @return       [type]                       [description]
     * @param [type] $[name] [<description>]
     *         yz_code  手机验证码
     *         u_type   1-个人用户  2-企业管理员  目前2
     */
	public function register_new(){
        if($this->request->isPost()){
            $redis = new Redis;
            $mobile = trim($this->request->param('mobile'));
            $username = trim($this->request->param('username')); 
            $password = trim($this->request->param('password')); 
            $password_confirm = trim($this->request->param('password_confirm'));
            $code = trim($this->request->param('yz_code'));
            $user_type = trim($this->request->param('u_type'));
            $confirm_code = $redis::get('pc_phone_Message_register_'.$mobile);
            if(!$confirm_code){$this->error('已超时,请重新提交',[],400);}

            if( empty($password) || empty($password_confirm) ||($password_confirm!=$password)){
                $this->error('密码不一致，请重新输入！',[],400);
            }
            if($code != $confirm_code){$this->error('验证码不正确',[],400);}
            $redis::del('pc_phone_Message_register_'.$mobile);
            //验证完成
            //插入数据库
            $indata = [
                'username' => $mobile,
                'password' => $username,
                'phone' => md5($password_confirm.Config::get('salt')),
                'authorize' => 9,
                'desc' => '后台注册用户-'.date('Y-m-d H:i:s',time()),
                'roleid' => 0,
            ];
            $res = Db::table('system_user')->insert($indata);
            //同步到dev

        }


    }
    /**
     * 发送验证码(注册)
     * @auth         false
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-10-09T10:02:28+0800
     * @LastTime     2020-10-09T10:02:28+0800
     * @return       [type]                       [description]
     * @param   $[name] [<description>]
     *          type   register   login
     */
    public function send_code(){
        $redis = new Redis;
        $type  =$this->request->param('type');
        $dbconf = $this->getconfig('vister_db');
        $mobile = $this->request->param('phone_num');
        $py_key = Db::connect($dbconf)->table('sysconfig')->where(['name'=>'Yunpian_Apikey'])->find();
        if($mobile==''){$this->error('手机号为空',['code'=>1],400);}
        if($type == 'register'){
            $check_uinfo = Db::connect($dbconf)->table('view_user')->where(['mobile'=>$mobile])->find();
            if($check_uinfo){

                $this->error('手机号存在,无需注册',['code'=>2],400);
                
            }
        }
        if($type == 'login'){
            $check_uinfo = Db::connect($dbconf)->table('view_user')->where(['mobile'=>$mobile])->find();
            if(!$check_uinfo){
                $this->error('用户不存在,请注册.',['code'=>3],400);
            }
        }
        //初始化client,apikey作为所有请求的默认值
        $clnt = YunpianClient::create($py_key['val']);
        $code = mt_rand(100000,999999);

        $param = [YunpianClient::MOBILE => $mobile ,YunpianClient::TEXT => '【智服网】您的验证码是'.$code];

        $redis_set_Str = $type =='register'?'pc_phone_Message_register_'.$mobile:'pc_phone_Message_login_'.$mobile;
        try{
            $r = $clnt->sms()->single_send($param);
            if($r->isSucc()){

                $redis::set($redis_set_Str,$code,300);
                //Cookie::set('Cookie_Message_'.$userinfo['db1']['id'] ,$code,1200);
                // var_dump($r->data());
                $this->success('验证码成功发送.',[],200);
                return true;
            }else{
                
                $this->error('验证码发送频繁,请等待一段时间再试.',[],400);
                return false;
            }
        }catch(Exception $e) {
            $this->error('验证码发送失败,请稍后再试.',[],400);
        }

    }

    /**
     * 退出系统
     * @auth false
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function out()
    {
        $this->app->session->clear();
        $this->app->session->destroy();
        $this->success('退出登录成功！', url('@admin/login'));
    }

}
